package com.net.j8583.field;

import com.net.j8583.Protocol8583;
import com.net.utils.ByteUtil;
import com.net.utils.StringUtils;

import java.nio.ByteBuffer;
import java.util.Map;

/**
 *
 * Date: 13-11-15
 * Time: 13:41
 */
public class FieldBitMap extends AbstractField {

    public FieldBitMap() {
        super(8, false);
    }


    @Override
    public byte[] toByte() {
        byte[] result = new byte[8];
        StringBuilder blockBuilder = new StringBuilder(8);
        StringBuilder fullStr = new StringBuilder();
        Map<Integer, Field> dataMap = i8583Request.getRequestData();
        for (int i = 1; i <= Protocol8583.FIELD_LEN; i++) {
            Field field = dataMap.get(i);
            if (field == null) {
                blockBuilder.append(StringUtils.STR_ZERO);
                fullStr.append(StringUtils.STR_ZERO);
            } else if (field.getReqSrcBytes().length == 0) {
                blockBuilder.append(StringUtils.STR_ZERO);
                fullStr.append(StringUtils.STR_ZERO);
            } else {
                blockBuilder.append(StringUtils.STR_ONE);
                fullStr.append(StringUtils.STR_ONE);
            }
        }
        if (i8583Request.isNeedMac()) {
            fullStr.replace(i8583Request.getMacFieldIndex() - 1, i8583Request.getMacFieldIndex(), StringUtils.STR_ONE);
        }
        int j = fullStr.length() / 8;
        for (int i = 0; i < j; i++) {
            String subStr = fullStr.substring(i * 8, i * 8 + 8);
            byte bit = ByteUtil.makeIntFromBinary(subStr);
            result[i] = bit;
        }
        reqEncodeByte = result;
        return result;
    }

    @Override
    public String getFieldType() {
        return VAR;
    }

    @Override
    public boolean isAutoFill() {
        return true;
    }

    @Override
    public int toValue(byte[] data, int index) {
        return 0;
    }

    @Override
    public void decode(ByteBuffer byteBuffer, Protocol8583 i8583Protocol) {

        for (int i = 0; i < 8; i++) {
            String str = ByteUtil.makeBinaryStr(byteBuffer.get());
            for (int j = 0; j < 8; j++) {
                String ss = str.substring(j, j + 1);
                if (StringUtils.STR_ONE.equals(ss)) {
                    continue;
                }
                int datafieldIndex = 8 * i + j + 1;
                i8583Protocol.removeResponseField(datafieldIndex);
            }
        }
        i8583Protocol.removeRedundancyHeaderField();
    }
}
